/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  JoinMemberActivity.java   
 * @Package com.jiyi.activity.new_maintenance   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-8-28 下午4:55:48   
 * @version V1.0     
 */
package com.jiyi.activity.datainput;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.datainput.sm.SignRecordActivity;
import com.jiyi.adapter.DIMemberAdapter;
import com.jiyi.adapter.PinyinComparator;
import com.jiyi.bean.zone.ZoneHaoYouBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.MaintenanceTaskListEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.ClearEditText;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.SysUtils;
import com.jiyi.widget.sortedcontact.sortlist.CharacterParser;
import com.jiyi.widget.sortedcontact.sortlist.SideBar;
import com.jiyi.widget.sortedcontact.sortlist.SideBar.OnTouchingLetterChangedListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: JoinMemberActivity
 * @Description:TODO(参与成员)
 * @author: HYM
 * @date: 2017-8-28 下午4:55:48
 * 
 */
public class DISignMemberActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.etSearch)
	ClearEditText etSearch;
	@BindView(R.id.sortlist)
	ListView sortlist;
	@BindView(R.id.sidrbar)
	SideBar sidrbar;

	private DIMemberAdapter adapter;
	private CharacterParser characterParser;
	private List<ZoneHaoYouBean> dataList = new ArrayList<ZoneHaoYouBean>();
	private PinyinComparator pinyinComparator;

	// 保存当前选择的好友
	ArrayList<String> idsList = new ArrayList<String>();
	// 之前选择的项目position,从哪里来的
	int position = -1, type = -1;
	Dialog dialog;
	// 任务id
	String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join_member);
		ButterKnife.bind(this);
		init();
	}

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	private void init() {
		setTop();
		getIntentData();
		// 实例化汉字转拼音类
		characterParser = new CharacterParser();
		pinyinComparator = new PinyinComparator();

		setAdapter();
		getData();
	}

	private void getIntentData() {
		setCurrentNum();
	}

	/**
	 * @author: HYM
	 * @Title: setAdapter
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-8-29
	 */
	private void setAdapter() {

		// 设置右侧触摸监听
		sidrbar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@SuppressLint("NewApi")
			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortlist.setSelection(position);
				}
			}
		});

		sortlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ZoneHaoYouBean zoneHaoYouBean = (ZoneHaoYouBean) parent
						.getAdapter().getItem(position);
				Intent intent = new Intent(view.getContext(),SignRecordActivity.class);
				intent.putExtra("userId", zoneHaoYouBean.getId());
				startActivity(intent);
				
			}
		});

		adapter = new DIMemberAdapter(this, dataList);
		sortlist.setAdapter(adapter);

		// 根据输入框输入值的改变来过滤搜索
		etSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	private void setTop() {
		tvTitle.setText("查看签到记录");
		tvSearch.setVisibility(View.GONE);
	}

	private void getData() {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("user_name", "");

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.DATA_INPUT_SQQX_MEMBER,
				"", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
//								JSONObject dataJson = new JSONObject(data);
//								String users = dataJson.getString("users");
								List<ZoneHaoYouBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<ZoneHaoYouBean>>() {
												}.getType());
								for (int i = 0; i < temp.size(); i++) {
									ZoneHaoYouBean haoyou = temp.get(i);
									// 汉字转换成拼音
									String pinyin = characterParser
											.getSellingWithPolyphone(haoyou
													.getName());
									String sortString = pinyin.substring(0, 1)
											.toUpperCase();

									// 正则表达式，判断首字母是否是英文字母
									if (sortString.matches("[A-Z]")) {
										haoyou.setSortLetters(sortString
												.toUpperCase());
									} else {
										haoyou.setSortLetters("#");
									}
								}

								dataList.clear();
								dataList.addAll(temp);

								for (int i = 0; i < dataList.size(); i++) {
									for (int j = 0; j < idsList.size(); j++) {
										if (dataList.get(i).getId()
												.equals(idsList.get(j))) {
											dataList.get(i).setIsCheck(true);
										}
									}
								}

								// 根据a-z进行排序源数据
								Collections.sort(dataList, pinyinComparator);
								adapter.notifyDataSetChanged();
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<ZoneHaoYouBean> filterDateList = new ArrayList<ZoneHaoYouBean>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = dataList;
		} else {
			filterDateList.clear();
			for (ZoneHaoYouBean sortModel : dataList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

	@OnClick({ R.id.tvBack, R.id.tvSearch })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			if (idsList.size() <= 0) {
				ToastUtil.getInstances().showMsg("请先选择参与成员");
				return;
			}
			saveMember();
			break;
		default:
			break;
		}
	}

	void saveIds(String id) {
		if (!idsList.contains(id)) {
			idsList.add(id);
		} else {
			idsList.remove(id);
		}
	}

	void setCurrentNum() {
		if (idsList.size() > 0) {
			tvSearch.setText("确定(" + idsList.size() + ")");
		} else {
			tvSearch.setText("确定");
		}
	}

	void saveMember() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		StringBuilder sbBuilder = new StringBuilder();
		for (int i = 0; i < idsList.size(); i++) {
			sbBuilder.append(idsList.get(i));
			sbBuilder.append(",");
		}

		String userList = SysUtils.SbToString(sbBuilder);

		if (!TextUtils.isEmpty(userList)) {
			params.put("member", userList);
		}

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_SAVE_JOIN_MEMBER, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								List<ZoneHaoYouBean> temp = new ArrayList<ZoneHaoYouBean>();
								for (int i = 0; i < dataList.size(); i++) {
									if (dataList.get(i).getIsCheck()) {
										temp.add(dataList.get(i));
									}
								}

								EventBus.getDefault().post(
										new MaintenanceTaskListEvent(type,
												position, temp, 2));

								finish();
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}
}
